package com.zzhrtech.wgzx_cityzen.ui.task;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.GsonRequest;
import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.zzhrtech.WgzxApplication;
import com.zzhrtech.wgzx_cityzen.Constans;
import com.zzhrtech.wgzx_cityzen.MainActivity;
import com.zzhrtech.wgzx_cityzen.R;
import com.zzhrtech.wgzx_cityzen.adapters.task.TaskListAdapter;
import com.zzhrtech.wgzx_cityzen.base.BaseFragment;
import com.zzhrtech.wgzx_cityzen.base.OnItemClickLitener;
import com.zzhrtech.wgzx_cityzen.beans.task.TaskListBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class TaskChildFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {

    private List<TaskListBean.Data> dataList;

    private TaskListAdapter listAdapter;
    private RecyclerView rc_task;

    private TextView emptyView;
    private SwipeToLoadLayout swipeToLoadLayout;
    private boolean viewReady = false;
    public TaskChildFragment() {
        // Required empty public constructor
    }

    public static TaskChildFragment newInstance() {
        
        Bundle args = new Bundle();
        TaskChildFragment fragment = new TaskChildFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view =  inflater.inflate(R.layout.fragment_task_child, container, false);

        viewReady = true;

        rc_task = (RecyclerView) view.findViewById(R.id.swipe_target);
        emptyView = (TextView) view.findViewById(R.id.emptyView);
        swipeToLoadLayout = (SwipeToLoadLayout) view.findViewById(R.id.swipeToLoadLayout);
        rc_task.setLayoutManager(new LinearLayoutManager(mActivity));
        rc_task.setItemAnimator(new DefaultItemAnimator());
        listAdapter = new TaskListAdapter();
        rc_task.setAdapter(listAdapter);

        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);

        listAdapter.setOnItemClickLitener(new OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(mActivity,TaskDetailActivity.class);
                intent.putExtra("taskid",dataList.get(position).getTask_id());
                intent.putExtra("now",dataList.get(position).getStatus());
                getActivity().startActivityForResult(intent,1);
            }
        });
        return view;
    }

    @Override
    protected void initData() {
        super.initData();

    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {

        if (!viewReady)
            return;

        if (isVisibleToUser){
            swipeToLoadLayout.setRefreshing(true);
        }

        super.setUserVisibleHint(isVisibleToUser);
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            swipeToLoadLayout.setRefreshing(false);
            dataList = (List<TaskListBean.Data>) msg.obj;

            if (dataList.size() == 0){
                emptyView.setVisibility(View.VISIBLE);
            }else {
                emptyView.setVisibility(View.GONE);

            for (TaskListBean.Data data : dataList){
//                Log.d("name=========]",data.getOneImgTh());
                listAdapter.addItem(data);
            }
            }

            return false;
        }
    });

    public void httpGetTasks(){

        Map<String,String> params = new HashMap<String, String>();
        params.put("citizen_id", ((MainActivity) mActivity).getCache().getAsString(Constans.keyUid));

        GsonRequest<TaskListBean> gsonRequest = new GsonRequest<TaskListBean>(com.android.volley.Request.Method.POST, Constans.HTTP_CITITASKLIST, TaskListBean.class, params, new com.android.volley.Response.Listener<TaskListBean>() {
            @Override
            public void onResponse(TaskListBean response) {

                if (response.isSuccess()){
                    Message message = new Message();
                    message.what = 0;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                }else {
                    emptyView.setVisibility(View.VISIBLE);
                    swipeToLoadLayout.setRefreshing(false);
//                    showToast(tv_time,response.getMsg());
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                swipeToLoadLayout.setRefreshing(false);
                Log.d("result=====",error + "");
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (swipeToLoadLayout.isRefreshing()) {
            swipeToLoadLayout.setRefreshing(false);
        }
        if (swipeToLoadLayout.isLoadingMore()) {
            swipeToLoadLayout.setLoadingMore(false);
        }
    }

    @Override
    public void onRefresh() {

        listAdapter.cleanList();
        httpGetTasks();

    }

    @Override
    public void onLoadMore() {

        swipeToLoadLayout.setLoadingMore(false);
    }
}
